package com.xiaomi.servlet;

import com.xiaomi.entity.*;
import com.xiaomi.service.AddressService;
import com.xiaomi.service.CartService;
import com.xiaomi.service.ItemService;
import com.xiaomi.service.OrderService;
import com.xiaomi.service.impl.AddressServiceImpl;
import com.xiaomi.service.impl.CartServiceImpl;
import com.xiaomi.service.impl.ItemServiceImpl;
import com.xiaomi.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/25
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {

    private final CartService cartService = new CartServiceImpl();
    private final AddressService addressService = new AddressServiceImpl();
    private final OrderService orderService = new OrderServiceImpl();
    private final ItemService itemService = new ItemServiceImpl();

    /**
     * 查询购物车和地址记录返回给order.jsp
     */
    protected String preView(HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        int uid = user.getUid();
        List<Cart> cartList = cartService.showCartsByUid(uid);
        List<Address> addList = addressService.showAddressesByUid(uid);
        req.setAttribute("cartList", cartList);
        req.setAttribute("addList", addList);
        return "forward:/order.jsp";
    }

    /**
     * 提交订单
     */
    protected String add(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        String aid = req.getParameter("aid");
        String sum = req.getParameter("sum");
        int count = orderService.addOrderAndItemList(uid, aid, sum);
        if (count > 0) {
            return "forward:/order?method=show&uid=" + uid;
        }
        req.setAttribute("msg", "提交订单失败");
        return "forward:/message.jsp";
    }

    /**
     * 查询订单信息
     */
    protected String show(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        List<Orders> list = orderService.getOrderSetAddress(uid);
        if (list != null) {
            req.setAttribute("orderList", list);
            return "forward:/orderList.jsp";
        }
        req.setAttribute("msg", "查询订单信息失败");
        return "forward:/message.jsp";
    }

    /**
     * 查询订单详细信息
     */
    protected String detail(HttpServletRequest req, HttpServletResponse resp) {
        String oid = req.getParameter("oid");
        Orders order = orderService.getOrder(oid);
        List<Item> items = itemService.itemList(oid);
        order.setList(items);
        req.setAttribute("od", order);
        return "forward:/orderDetail.jsp";
    }
}
